package org.cnam.mobileShopping.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.cnam.mobileShopping.bean.Contact;

import android.app.Activity;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.util.Log;

/**
 * Gestionnaire des contacts du téléphone
 * 
 * @author laurent
 * 
 */
public class ContactController {

	/**
	 * Permet de récupérer tous les contacts présent sur le téléphone qui ont un
	 * numéro de téléphone
	 * 
	 * @param activity
	 * @return
	 */
	public static List<? extends Map<String, ?>> retrieveContacts(
			Activity activity) {

		// la map a retourner
		List<Map<String, Contact>> toReturn = new ArrayList<Map<String, Contact>>();
		// Build adapter with contact entries
		Cursor contacts = getContacts(activity);

		String name, number;
		Uri phoneUri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
		String[] PHONES_PROJECTION = new String[] { ContactsContract.CommonDataKinds.Phone.NUMBER };
		String PHONE_SELECTION = null;

		contacts.moveToFirst();

		do {

			String contactId = contacts.getString(contacts
					.getColumnIndex(ContactsContract.Contacts._ID));

			PHONE_SELECTION = ContactsContract.CommonDataKinds.Phone.CONTACT_ID
					+ "=" + contactId;

			Cursor phones = activity.managedQuery(phoneUri, PHONES_PROJECTION,
					PHONE_SELECTION, null,
					ContactsContract.CommonDataKinds.Phone.IS_SUPER_PRIMARY
							+ " DESC");
			phones.moveToFirst();
			if (phones != null) {

				do {
					try {

						number = phones
								.getString(phones
										.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
						if (number.startsWith("06") || number.startsWith("07")) {
							name = contacts
									.getString(contacts
											.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));

							Map<String, Contact> toAdd = new HashMap<String, Contact>();
							toAdd.put("line1", new Contact(name, number));
							toReturn.add(toAdd);
						}
					} catch (Exception e) {
						Log.i("ContactController", e.getMessage());
					}
				} while (phones.moveToNext());
				phones.close();
			}
		} while (contacts.moveToNext());
		contacts.close();

		return toReturn;
	}

	/**
	 * Obtains the contact list for the currently selected account.
	 * 
	 * @return A cursor for for accessing the contact list.
	 */
	private static Cursor getContacts(Activity activity) {
		Uri contactUri = ContactsContract.Contacts.CONTENT_URI;

		String[] projection = new String[] { ContactsContract.Contacts._ID,
				ContactsContract.Contacts.DISPLAY_NAME,
				ContactsContract.Contacts.HAS_PHONE_NUMBER, };

		// pour ne prendre que les contacts ayant un numéro de téléphone
		String selection = ContactsContract.Contacts.HAS_PHONE_NUMBER + "='1'";

		return activity.managedQuery(contactUri, projection, selection, null,
				ContactsContract.Contacts.DISPLAY_NAME + " ASC");
	}

}
